package com.yunc.base.queue.disruptor;

import com.google.common.base.Preconditions;
import com.lmax.disruptor.EventHandler;
import com.yunc.base.utils.ClassUtil;

import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author taocongcong
 * @create 2020-08-15 9:19
 */
public class EventHandlerProcess {

    public Set<EventHandler> scanHandlers(){
        List<Class<?>> clsList = ClassUtil.getAllClassByPackageName("com.yunc");
        return clsList.stream()
                .filter(p->p.getAnnotation(Handler.class)!=null)
                .map(c-> {
                    try {
                        return (EventHandler)c.newInstance();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                    return null;
                })
                .collect(Collectors.toSet());

    }

    public EventHandler scanJavaClass(Class cls) throws IllegalAccessException, InstantiationException {
        Annotation annotation = cls.getAnnotation(Handler.class);
        if (annotation != null) {
            Object instance = cls.newInstance();
            //是否可以做成动态字节码生成，框架内部完成接口类的实现
            Preconditions.checkState(instance instanceof EventHandler);
            return (EventHandler) instance;
        }
        return null;
    }

    public static void main(String[] args) {
        String classPath = (String) System.getProperties().get("java.class.path");
        List<String> packages = Arrays.stream(classPath.split(";")).filter(p -> p.contains("demo-disruptor-project")).collect(Collectors.toList());
        // List<Class<?>> clsList = ClassUtil.getAllClassByPackageName(BlackPeople.class.getPackage());
        List<Class<?>> clsList = ClassUtil.getAllClassByPackageName("com.yunc");
        System.out.println(clsList);
    }
}
